<?php

namespace addon\lian\shop\controller;

use addon\lian\model\Config as ConfigModel;
use addon\lian\model\LianMember;
use addon\lian\model\LianLevel as LianLevelModel;
use addon\lian\model\sqlmodel\LianMemberModel;
use addon\lian\model\sqlmodel\LianPubLineModel;
use app\model\goods\Goods as GoodsModel;
use app\model\member\Member as MemberModel;
use app\shop\controller\BaseShop;
use think\App;
use think\facade\Log;
use think\facade\Db;

/**
 *  会员设置
 */
class Member extends BaseShop
{
    public function __construct(App $app = null)
    {
        $this->replace = [
            'LIAN_JS' => __ROOT__ . '/addon/lian/shop/view/public/js',
            'LIAN_CSS' => __ROOT__ . '/addon/lian/shop/view/public/css'
        ];
        parent::__construct($app);
    }

    /**
     * 会员概况
     */
    public function index()
    {
        return $this->fetch('member/index');
    }

    public function stat()
    {
        $data = [
            'account_data' => [],
            'fenxiao_account' => 0.00,
            'shop_commission' => [],
            'shop_commission_end' => [],
            'commission_money' => 0.00,
            'fenxiao_apply_num' => 0,
            'fenxiao_num' => 0,
            'fenxiao_goods_num' => 0
        ];

        $fenxiao_data_model = new FenxiaoData();
        $account_data = $fenxiao_data_model->getFenxiaoAccountData($this->site_id);
        $data['account_data'] = $account_data;

        //累计佣金
        $fenxiao_account = number_format($account_data[ 'account' ], 2, '.', '');
        $data['fenxiao_account'] = $fenxiao_account;

        //获取分销的总金额
        $order_model = new FenxiaoOrderModel();
        $commission = $order_model->getFenxiaoOrderInfo([ [ 'site_id', '=', $this->site_id ] ], 'sum(real_goods_money) as real_goods_money,sum(commission) as commission')[ 'data' ];
        if ($commission[ 'real_goods_money' ] == null) {
            $commission[ 'real_goods_money' ] = '0.00';
        }
        if ($commission[ 'commission' ] == null) {
            $commission[ 'commission' ] = '0.00';
        }
        $data['shop_commission'] = $commission;

        //获取已结算分销的总金额
        $commission_end = $order_model->getFenxiaoOrderInfo([ [ 'site_id', '=', $this->site_id ], [ 'is_settlement', '=', 1 ], [ 'is_refund', '=', 0 ] ], 'sum(real_goods_money) as real_goods_money,sum(commission) as commission')[ 'data' ];
        if ($commission_end[ 'real_goods_money' ] == null) {
            $commission_end[ 'real_goods_money' ] = '0.00';
        }
        if ($commission_end[ 'commission' ] == null) {
            $commission_end[ 'commission' ] = '0.00';
        }
        $data['shop_commission_end'] = $commission_end;

        //获取已退款的佣金
        $commission_refund = $order_model->getFenxiaoOrderInfo([ [ 'site_id', '=', $this->site_id ], [ 'is_refund', '=', 1 ] ], 'sum(real_goods_money) as real_goods_money,sum(commission) as commission')[ 'data' ];
        if ($commission_refund[ 'real_goods_money' ] == null) {
            $commission_refund[ 'real_goods_money' ] = '0.00';
        }
        if ($commission_refund[ 'commission' ] == null) {
            $commission_refund[ 'commission' ] = '0.00';
        }
        $commission_money = round($commission[ 'commission' ], 2) - round($commission_end[ 'commission' ], 2) - round($commission_refund[ 'commission' ], 2);
        $commission_money = number_format($commission_money, 2);
        $data['commission_money'] = $commission_money;

        $fenxiao_apply_num = $fenxiao_data_model->getFenxiaoApplyCount($this->site_id);
        $data['fenxiao_apply_num'] = $fenxiao_apply_num;

        //分销商人数
        $fenxiao_num = $fenxiao_data_model->getFenxiaoCount($this->site_id);
        $data['fenxiao_num'] = $fenxiao_num;

        $goods_model = new GoodsModel();
        $fenxiao_goods_num = $goods_model->getGoodsInfo([ [ 'site_id', '=', $this->site_id ], [ 'is_fenxiao', '=', 1 ], [ 'is_delete', '=', 0 ] ], 'count(goods_id) as fenxiao_goods_num')[ 'data' ];
        $data['fenxiao_goods_num'] = $fenxiao_goods_num[ 'fenxiao_goods_num' ];

        return $data;
    }


    /**
     * 会员列表
     */
    public function lists()
    {
        $model = new LianMember();
        if (request()->isJson()) {

            $nickname = input('nickname', '');
            $mobile = input('mobile', '');
            $level_id = input('level_id', '');
            $start_time = input('start_time', '');
            $end_time = input('end_time', '');
            $status = input('status', '');

            // 可以选择使用关联查询（推荐）或原始查询
            $use_relation = input('use_relation', 1); // 默认使用关联查询

            $page = input('page', 1);
            $page_size = input('page_size', PAGE_LIST_ROWS);

            if ($use_relation) {
                // 使用模型关联查询 - 不使用表别名
                $condition = [];
                $condition[] = [ 'site_id', '=', $this->site_id ];

                if ($level_id) {
                    $condition[] = [ 'level_id', '=', $level_id ];
                }
                if ($start_time && $end_time) {
                    $condition[] = [ 'create_time', 'between', [ date_to_time($start_time), date_to_time($end_time) ] ];
                } elseif (!$start_time && $end_time) {
                    $condition[] = [ 'create_time', '<=', date_to_time($end_time) ];
                } elseif ($start_time && !$end_time) {
                    $condition[] = [ 'create_time', '>=', date_to_time($start_time) ];
                }

                if (!empty($status)) {
                    $condition[] = [ 'status', '=', $status ];
                }

                $list = (new LianMember)->getPage($this->site_id, $condition, $page, $page_size);
                // $list = $model->getLianMemberPageListWithRelation($condition, $page, $page_size, 'create_time desc', $nickname, $mobile);
            }

            return $list;

        } else {
            $level_model = new LianLevelModel();
            $level_list = $level_model->getLevelList([ [ 'status', '=', 1 ], [ 'site_id', '=', $this->site_id ] ], 'level_id,level_name,level_num')[ 'data' ];
            $this->assign('level_list', $level_list);

            $config_model = new ConfigModel();
            $basics = $config_model->getLianBasicsConfig($this->site_id)[ 'data' ][ 'value' ];
            $this->assign('basics_info', $basics);

            return $this->fetch('member/lists');
        }
    }

    /**
     * 添加链动会员
     */
    public function add()
    {
        if (request()->isJson()) {

            $lian_data = [
                'site_id' => $this->site_id,
                'member_id' => input('member_id', 0),//关联会员ID
                'pid' => input('pid', 0),//上级ID
            ];
            $model = new LianMember();
            return $model->addLianMember($lian_data);

        } else {

            //获取链动等级
            $level_model = new LianLevelModel();
            $level_list = $level_model->getLevelList([ [ 'status', '=', 1 ], [ 'site_id', '=', $this->site_id ] ], 'level_id,level_name,level_num')[ 'data' ];
            $this->assign('level_list', $level_list);

            //获取会员列表
            $member_model = new MemberModel();
            $where[] = [ 'site_id', '=', $this->site_id ];
            $member_list = $member_model->getMemberList($where, 'member_id,nickname,headimg')[ 'data' ];
            $this->assign('member_list', $member_list);

            return $this->fetch('member/add');
        }

    }

    /**
     * 删除链动会员
     */
    public function delete(){
        $model = new LianMember();

        $id = input('id', '');
        $res = $model->deleteMember($id, $this->site_id);
        return $res;
    }


    /**
     * 获取会员列表
     */
    public function getMemberList()
    {
        $page_index = input('page', 1);
        $page_size = input('page_size', PAGE_LIST_ROWS);
        $member_search = input('member_search', '');
        $condition = [];
        $condition[] = [ 'mobile|email|username|nickname', 'like', '%' . $member_search . '%' ];
        $condition[] = [ 'site_id', '=', $this->site_id ];
        $member_model = new MemberModel();
        $list = $member_model->getMemberPageList($condition, $page_index, $page_size, '', 'member_id,headimg,nickname,point,balance');
        return $list;
    }

    /**
     * 详情
     */
    public function detail()
    {
        $fenxiao_id = input('fenxiao_id', '');

        $model = new FenxiaoModel();
        $fenxiao_leve_model = new FenxiaoLevelModel();

        $condition[] = [ 'f.fenxiao_id', '=', $fenxiao_id ];
        $info = $model->getFenxiaoDetailInfo($condition);
        if (empty($info[ 'data' ])) $this->error('未获取到分销商数据', href_url('fenxiao://shop/fenxiao/lists'));
        //团队人员数据
        $info['data']['team_num'] = $model->getFenxiaoTeamNum($fenxiao_id, $this->site_id)['data'];

        $fenxiao_level = $fenxiao_leve_model->getLevelInfo([ [ 'level_id', '=', $info[ 'data' ][ 'level_id' ] ] ]);

        $this->assign('status', $model->fenxiao_status_zh);
        $this->assign('level', $fenxiao_level[ 'data' ]);
        $this->assign('info', $info[ 'data' ]);

        $this->assign('fenxiao_id', $fenxiao_id);

        $config_model = new ConfigModel();
        $basics_config = $config_model->getFenxiaoBasicsConfig($this->site_id);
        $this->assign('fenxiao_level_num', $basics_config[ 'data' ][ 'value' ][ 'level' ]);

        return $this->fetch('fenxiao/fenxiao_detail');
    }


    /**
     * 冻结
     */
    public function frozen()
    {
        $member_id = input('member_id', '');
        $model = new LianMember();
        return $model->frozen($member_id);
    }

    /**
     * 恢复正常
     */
    public function unfrozen()
    {
        $member_id = input('member_id', '');
        $model = new LianMember();
        return $model->unfrozen($member_id);
    }

    


    /**
     * 变更上下级
     */
    public function change()
    {
        $member_id = input('member_id');
        $model = new FenxiaoModel();
        $member_model = new MemberModel();

        //用户信息
        $member_info = $member_model->getMemberInfo([ [ 'member_id', '=', $member_id ] ], 'fenxiao_id,is_fenxiao')[ 'data' ];
        //获取分销信息
        $fenxiao_info = $model->getFenxiaoInfo([ [ 'fenxiao_id', '=', $member_info[ 'fenxiao_id' ] ] ], 'parent');
        //获取上级分销商信息
        $parent_info = [];
        if (!empty($fenxiao_info[ 'data' ])) {
            $parent_info = $model->getFenxiaoInfo([ [ 'fenxiao_id', '=', $fenxiao_info[ 'data' ][ 'parent' ] ] ], 'fenxiao_id,fenxiao_name')['data'];
        }
        if (request()->isJson()) {
            if ($member_info[ 'is_fenxiao' ] == 1) {
                $condition[] = [ 'f.fenxiao_id', '<>', $member_info[ 'fenxiao_id' ] ];
                $condition[] = [ 'f.parent', '<>', $member_info[ 'fenxiao_id' ] ];
            }

            $condition[] = [ 'f.site_id', '=', $this->site_id ];
            $status = input('status', 1);
            if ($status) {
                $condition[] = [ 'f.status', '=', $status ];
            }

            $fenxiao_name = input('fenxiao_name', '');
            if ($fenxiao_name) {
                $condition[] = [ 'f.fenxiao_name', 'like', '%' . $fenxiao_name . '%' ];
            }

            $parent_name = input('parent_name', '');
            if ($parent_name) {
                $condition[] = [ 'pf.fenxiao_name', 'like', '%' . $parent_name . '%' ];
            }

            $level_id = input('level_id', '');
            if ($level_id) {
                $condition[] = [ 'f.level_id', '=', $level_id ];
            }
            $start_time = input('start_time', '');
            $end_time = input('end_time', '');
            if ($start_time && $end_time) {
                $condition[] = [ 'f.create_time', 'between', [ date_to_time($start_time), date_to_time($end_time) ] ];
            } elseif (!$start_time && $end_time) {
                $condition[] = [ 'f.create_time', '<=', date_to_time($end_time) ];

            } elseif ($start_time && !$end_time) {
                $condition[] = [ 'f.create_time', '>=', date_to_time($start_time) ];
            }
            if(!empty($parent_info)){
                $order = \think\facade\Db::raw("IF(f.fenxiao_id = {$parent_info['fenxiao_id']}, 1, 2) asc,f.create_time desc");
            }else{
                $order = 'f.create_time desc';
            }

            $page = input('page', 1);
            $page_size = input('page_size', PAGE_LIST_ROWS);
            $list = $model->getFenxiaoPageList($condition, $page, $page_size, $order);
            return $list;

        } else {
            $level_model = new FenxiaoLevelModel();
            $level_list = $level_model->getLevelList([ [ 'status', '=', 1 ], [ 'site_id', '=', $this->site_id ] ], 'level_id,level_name');
            $this->assign('level_list', $level_list[ 'data' ]);

            $config_model = new ConfigModel();
            $basics = $config_model->getFenxiaoBasicsConfig($this->site_id);
            $this->assign('basics_info', $basics[ 'data' ][ 'value' ]);

            $this->assign('member_id', $member_id);
            $this->assign('parent_info', $parent_info);

            $change_end_func = input('change_end_func', 'changeEnd');
            $this->assign('change_end_func', $change_end_func);

            return $this->fetch('fenxiao/change');
        }
    }

    /**
     * 确认变更
     */
    public function confirmChange()
    {
        if (request()->isJson()) {

            $member_id = input('member_id', '');
            $parent = input('parent', '');
            $type = input('type', '');
            $model = new FenxiaoModel();
            if ($type == 1) {
                $res = $model->changeParentFenxiao($member_id, $parent);
            } else {
                $res = $model->cancelParentFenxiao($member_id);
            }

            return $res;
        }
    }

    /**
     * 会员详情
     */
    public function memberInfo()
    {
        if (request()->isJson()) {

            $member_id = input('member_id', '');
            $condition[] = [ 'site_id', '=', $this->site_id ];
            $condition[] = [ 'member_id', '=', $member_id ];
            $member_model = new MemberModel();
            $member_info_result = $member_model->getMemberInfo($condition);
            $member_info = $member_info_result['data'];
            if (empty($member_info)) return $member_model->error([], '账号不存在！');
            return $member_info_result;
        }
    }

    /**
     * 修改链动会员等级
     */
    public function changeLevel()
    {
        $member_id = input('member_id', '');
        $lian_id = input('lian_id', '');
        if (request()->isJson()) {
            $level_model = new LianLevelModel();
            $lian_model = new LianMember();
            $lian_info = $lian_model->getLianMemberInfo([ [ 'lian_id', '=', $lian_id ] ], 'member_id,level_id,level_name')[ 'data' ];
            $condition[] = [ 'site_id', '=', $this->site_id ];
            if (!empty($lian_info)) {
                $condition[] = [ 'level_id', '<>', $lian_info[ 'level_id' ] ];
            }

            $lists = $level_model->getLevelPageList($condition, '1', PAGE_LIST_ROWS, 'level_num asc');
            return $lists;
        } else {
            $config_model = new ConfigModel();
            $basics = $config_model->getLianBasicsConfig($this->site_id);
            $this->assign('basics_info', $basics[ 'data' ][ 'value' ]);

            $this->assign('member_id', $member_id);

            $this->assign('lian_id', $lian_id);

            $change_end_func = input('change_end_func', 'changeEnd');
            $this->assign('change_end_func', $change_end_func);

            return $this->fetch('member/change_level');
        }

    }

    /**
     * 确认变更
     */
    public function confirmChangeLevel()
    {
        if (request()->isJson()) {

            $member_id = input('member_id', '');
            $level_id = input('level_id', '');

            $level_model = new LianLevelModel();
            $level_data = $level_model->getLevelInfo([ [ 'level_id', '=', $level_id ] ], 'level_id,level_name')[ 'data' ];
            $lian_model = new LianMember();
            $data = [
                'level_id' => $level_data[ 'level_id' ],
                'level_name' => $level_data[ 'level_name' ]
            ];
            $res = $lian_model->changeLianMemberLevel($data, [ [ 'member_id', '=', $member_id ] ]);
            return $res;
        }
    }


    /**
     * 公排会员关系图
     */
    public function charts()
    {
        $mid = input('mid', 0);
        $member = [];
        $deeplevel = 1;
        $parent_info = null;
        $has_parent = false;
        $error_message = '';

        if ($mid > 0) {
            try {
                $member_model = new LianPubLineModel();

                // 检查会员是否存在
                $member_basic = Db::name('member')
                    ->where('member_id', $mid)
                    ->where('site_id', $this->site_id)
                    ->field('member_id,nickname,headimg')
                    ->find();

                if (empty($member_basic)) {
                    $error_message = "会员ID({$mid})不存在或不属于当前站点";
                } else {
                    // 查询公排信息
                    $publine_info = $member_model->where('site_id', $this->site_id)
                        ->where('member_id', $mid)
                        ->find();

                    if (!empty($publine_info)) {
                        // 构建会员数据
                        $member = [
                            'member_id' => (int)$publine_info['member_id'],
                            'pid' => (int)($publine_info['pid'] ?? 0),
                            'up_pid' => (int)($publine_info['up_pid'] ?? 0),
                            'level' => (int)($publine_info['level'] ?? 1),
                            'position' => (int)($publine_info['position'] ?? 1),
                            'nickname' => $member_basic['nickname'] ?? '未知会员',
                            'headimg' => $member_basic['headimg'] ?: '/static/img/touxiang.png',
                            'team_count' => (int)($publine_info['team_count'] ?? 0),
                            'direct_count' => (int)($publine_info['direct_count'] ?? 0),
                        ];

                        // 构建显示名称
                        if ($member['pid'] == 0) {
                            $member['name'] = $member['nickname'] . '(ID:' . $member['member_id'] . ',根节点)';
                        } else {
                            $member['name'] = $member['nickname'] . '(ID:' . $member['member_id'] . ',推荐人:' . $member['pid'] . ')';
                        }

                        // 获取下级会员
                        $member['children'] = $member_model->getPublineChildren($member['member_id'], 0, []);

                        // 计算层级深度
                        $deeplevel = $this->calculateDeepLevel($member);

                        // 获取上级信息
                        if ($member['up_pid'] > 0) {
                            $parent_publine = $member_model->where('site_id', $this->site_id)
                                ->where('member_id', $member['up_pid'])
                                ->find();

                            if (!empty($parent_publine)) {
                                $parent_basic = Db::name('member')
                                    ->where('member_id', $member['up_pid'])
                                    ->field('member_id,nickname,headimg')
                                    ->find();

                                if (!empty($parent_basic)) {
                                    $parent_info = [
                                        'member_id' => $parent_publine['member_id'],
                                        'nickname' => $parent_basic['nickname'] ?? '未知会员',
                                        'headimg' => $parent_basic['headimg'] ?: '/static/img/touxiang.png',
                                    ];
                                    $has_parent = true;
                                }
                            }
                        }
                    } else {
                        $error_message = "会员({$mid})没有公排数据";
                    }
                }
            } catch (\Exception $e) {
                $error_message = "查询会员关系图时发生错误: " . $e->getMessage();
                Log::error('Charts Error: ' . $e->getMessage());
            }
        }

        // 确保数据格式正确，转换为JSON字符串
        $member_json = $member ? json_encode($member, JSON_UNESCAPED_UNICODE) : '';
        
        $this->assign('member', $member);
        $this->assign('member_json', $member_json);
        $this->assign('deeplevel', $deeplevel);
        $this->assign('parent_info', $parent_info);
        $this->assign('has_parent', $has_parent);
        $this->assign('error_message', $error_message);
        
        return $this->fetch('member/charts');
    }

    /**
     * 构建树形数据
     * @param array $member_info 会员信息
     * @param object $member_model 会员模型
     * @return array
     */
    private function buildTreeData($member_info, $member_model)
    {
        // 获取会员基本信息
        $member = [
            'member_id' => $member_info['member_id'],
            'pid' => $member_info['pid'],
            'up_pid' => $member_info['up_pid'] ?? 0,
            'nickname' => $member_info['member']['nickname'] ?? '未知会员',
            'headimg' => $member_info['member']['headimg'] ?? '/static/img/touxiang.png',
        ];

        // 构建显示名称：昵称(ID:会员ID,推荐人:推荐人ID)
        $member['name'] = $member['nickname'] . '(ID:' . $member['member_id'] . ',推荐人:' . $member['pid'] . ')';

        // 递归获取下级会员
        $member['children'] = $member_model->getPublineChildren($member_info['member_id'], 0, []);

        return $member;
    }

    /**
     * 计算关系图的深度
     * @param array $member 会员数据
     * @param int $level 当前层级
     * @return int
     */
    private function calculateDeepLevel($member, $level = 1)
    {
        $maxLevel = $level;

        if (isset($member['children']) && !empty($member['children'])) {
            foreach ($member['children'] as $child) {
                $childLevel = $this->calculateDeepLevel($child, $level + 1);
                $maxLevel = max($maxLevel, $childLevel);
            }
        }

        return $maxLevel;
    }

    /**
     * 获取会员的上级关系链
     * @param int $member_id 会员ID
     * @return array 上级关系链
     */
    private function getMemberParentChain($member_id)
    {
        $chain = [];
        $member_model = new LianPubLineModel();

        $current_member = $member_model->where('site_id', $this->site_id)
            ->where('member_id', $member_id)
            ->find();

        while (!empty($current_member) && $current_member['up_pid'] > 0) {
            $parent = $member_model->where('site_id', $this->site_id)
                ->where('member_id', $current_member['up_pid'])
                ->find();

            if (!empty($parent)) {
                $parent_basic = Db::name('member')
                    ->where('member_id', $parent['member_id'])
                    ->field('member_id,nickname,headimg')
                    ->find();

                if (!empty($parent_basic)) {
                    array_unshift($chain, [
                        'member_id' => $parent['member_id'],
                        'nickname' => $parent_basic['nickname'] ?? '未知会员',
                        'level' => $parent['level'] ?? 1,
                    ]);
                }
                $current_member = $parent;
            } else {
                break;
            }
        }

        return $chain;
    }

    /**
     * 测试公排数据
     */
    public function testCharts()
    {
        $mid = input('mid', 1);

        // 直接查询数据库测试
        $member_model = new LianPubLineModel();
        $member_info = $member_model->where('site_id', $this->site_id)
            ->where('member_id', $mid)
            ->find();

        if (empty($member_info)) {
            echo "未找到会员ID为 {$mid} 的公排数据";
            return;
        }

        // 获取会员基本信息
        $member_basic = \think\facade\Db::name('member')
            ->where('member_id', $mid)
            ->field('member_id,nickname,headimg')
            ->find();

        if (empty($member_basic)) {
            echo "未找到会员ID为 {$mid} 的基本信息";
            return;
        }

        // 构建简单的测试数据
        $test_data = [
            'member_id' => $member_info['member_id'],
            'pid' => $member_info['pid'],
            'up_pid' => $member_info['up_pid'],
            'nickname' => $member_basic['nickname'],
            'headimg' => $member_basic['headimg'] ?: '/static/img/touxiang.png',
            'name' => $member_basic['nickname'] . '(ID:' . $member_info['member_id'] . ',推荐人:' . $member_info['pid'] . ')',
            'children' => []
        ];

        // 获取下级
        $children = $member_model->where('site_id', $this->site_id)
            ->where('up_pid', $mid)
            ->select();

        foreach ($children as $child) {
            $child_basic = \think\facade\Db::name('member')
                ->where('member_id', $child['member_id'])
                ->field('member_id,nickname,headimg')
                ->find();

            if ($child_basic) {
                $test_data['children'][] = [
                    'member_id' => $child['member_id'],
                    'pid' => $child['pid'],
                    'up_pid' => $child['up_pid'],
                    'nickname' => $child_basic['nickname'],
                    'headimg' => $child_basic['headimg'] ?: '/static/img/touxiang.png',
                    'name' => $child_basic['nickname'] . '(ID:' . $child['member_id'] . ',推荐人:' . $child['pid'] . ')',
                    'children' => []
                ];
            }
        }

        $this->assign('member', $test_data);
        $this->assign('deeplevel', 2);
        return $this->fetch('member/test_charts');
    }

    /**
     * 简化版会员关系图
     */
    public function chartsSimple()
    {
        // 处理页面显示
        $mid = input('mid', 1); // 默认显示ID为1的会员
        $member = [];
        $deeplevel = 1;

        if ($mid > 0) {
            $member_model = new LianPubLineModel();

            // 查询公排会员信息
            $publine_info = $member_model->where('site_id', $this->site_id)
                ->where('member_id', $mid)
                ->find();

            // 如果公排表中没有数据，但会员表中有数据，则创建基础数据
            if (empty($publine_info)) {
                // 查询会员基本信息
                $member_basic = Db::name('member')
                    ->where('member_id', $mid)
                    ->field('member_id,nickname,headimg')
                    ->find();

                if (!empty($member_basic)) {
                    // 为根节点创建基础公排数据
                    $publine_info = [
                        'member_id' => $mid,
                        'pid' => 0,
                        'up_pid' => 0,
                        'level' => 1,
                        'position' => 1,
                        'site_id' => $this->site_id
                    ];
                }
            }

            if (!empty($publine_info)) {
                // 查询会员基本信息（如果之前没有查询过）
                if (!isset($member_basic)) {
                    $member_basic = Db::name('member')
                        ->where('member_id', $mid)
                        ->field('member_id,nickname,headimg')
                        ->find();
                }

                if (!empty($member_basic)) {
                    // 构建会员数据
                    $member = [
                        'member_id' => $publine_info['member_id'],
                        'pid' => $publine_info['pid'] ?? 0,
                        'up_pid' => $publine_info['up_pid'] ?? 0,
                        'level' => $publine_info['level'] ?? 1,
                        'position' => $publine_info['position'] ?? 1,
                        'nickname' => $member_basic['nickname'] ?? '未知会员',
                        'headimg' => $member_basic['headimg'] ?: '/static/img/touxiang.png',
                    ];

                    // 构建显示名称 - 根节点特殊处理
                    if ($member['pid'] == 0) {
                        $member['name'] = $member['nickname'] . '(ID:' . $member['member_id'] . ',根节点)';
                    } else {
                        $member['name'] = $member['nickname'] . '(ID:' . $member['member_id'] . ',推荐人:' . $member['pid'] . ')';
                    }

                    // 递归获取下级会员
                    $member['children'] = $member_model->getPublineChildren($member['member_id'], 0, []);

                    // 计算层级深度
                    $deeplevel = $this->calculateDeepLevel($member);
                }
            }
        }

        $this->assign('member', $member);
        $this->assign('deeplevel', $deeplevel);
        return $this->fetch('member/charts_simple');
    }


    /**
     * 获取会员关系图数据（AJAX接口）
     */
    public function getChartsData()
    {
        if (!request()->isJson()) {
            return $this->error('请求方式错误');
        }

        $mid = input('mid', 0);
        if ($mid <= 0) {
            return $this->error('会员ID不能为空');
        }

        $member_model = new LianPubLineModel();

        // 查询公排会员信息
        $publine_info = $member_model->where('site_id', $this->site_id)
            ->where('member_id', $mid)
            ->find();

        if (empty($publine_info)) {
            return $this->error('未找到该会员的公排信息');
        }

        // 查询会员基本信息
        $member_basic = Db::name('member')
            ->where('member_id', $mid)
            ->field('member_id,nickname,headimg')
            ->find();

        if (empty($member_basic)) {
            return $this->error('未找到该会员信息');
        }

        // 构建会员数据
        $member = [
            'member_id' => $publine_info['member_id'],
            'pid' => $publine_info['pid'],
            'up_pid' => $publine_info['up_pid'] ?? 0,
            'level' => $publine_info['level'] ?? 1,
            'position' => $publine_info['position'] ?? 1,
            'nickname' => $member_basic['nickname'] ?? '未知会员',
            'headimg' => $member_basic['headimg'] ?: '/static/img/touxiang.png',
        ];

        // 构建显示名称
        $member['name'] = $member['nickname'] . '(ID:' . $member['member_id'] . ',推荐人:' . $member['pid'] . ')';

        // 递归获取下级会员
        $member['children'] = $member_model->getPublineChildren($member['member_id'], 0, []);

        // 获取上级关系链
        $parent_chain = $this->getMemberParentChain($member['member_id']);

        // 计算层级深度
        $deeplevel = $this->calculateDeepLevel($member);

        return $this->success([
            'member' => $member,
            'deeplevel' => $deeplevel,
            'parent_chain' => $parent_chain,
            'has_parent' => $member['up_pid'] > 0
        ]);
    }



}